package com.yuyu.commons.toolKit;

import okhttp3.*;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/12/26 0026.
 */
public class HttpUtil {
    public static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/x-markdown; charset=utf-8");
    public static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/png");
    public static final MediaType MEDIA_TYPE_AUDIO = MediaType.parse("audio/mp3");
    public static final MediaType MEDIA_TYPE_VIDEO = MediaType.parse("video/mp4");
    public static final MediaType MEDIA_TYPE_OBJECT = MediaType.parse("application/octet-stream");
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");


    public static final int DEFAULT_TIMEOUT = 30;


    public static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .build();


    public static String sendOkPost(String url, String json) throws IOException {
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    public static String sendOkPost(String url, Map<String, String> param) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static String sendOkPost(String url, String authorization, Map<String, String> param) throws IOException {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        Request request = new Request.Builder().header("Content-Type", "text/html;charset=utf-8").header("accept-charset", "UTF-8").header("authorization", authorization).url(url).post(builder.build()).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static String sendFromDataPostRequest(String url, File file, String typeName, Map<String, String> map, MediaType mediaType) throws IOException {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        builder.setType(MultipartBody.FORM).addFormDataPart(typeName, file.getName(), RequestBody.create(file, mediaType));
        RequestBody requestBody = builder.setType(MultipartBody.FORM)
                .addFormDataPart(typeName, file.getName(), RequestBody.create(mediaType, file))
                .build();
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        return client.newCall(request).execute().body().string();
    }

    /**
     * 发送短信
     *
     * @param url           短信接口
     * @param authorization 授权
     * @param json          body体参数
     * @return
     * @throws IOException
     */
    public static String sendOkPost(String url, String authorization, String json) throws IOException {
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .header("authorization", authorization)
                .header("accept", "application/json")
                .url(url).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();

    }

    public static String sendOkGet(String url) throws IOException {
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        Request request = new Request.Builder()
                .header("accept", "application/json")
                .url(url).get().build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static String sendOkDel(String url) throws IOException {
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        Request request = new Request.Builder()
                .header("accept", "application/json")
                .url(url).delete().build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 发送POST请求
     *
     * @param strURL
     * @param json
     * @return
     * @throws IOException
     */
    public static String sendPostJSON(String strURL, String json) throws IOException {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.connect();
        connection.setConnectTimeout(DEFAULT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_TIMEOUT);
        //写入JSON
        try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
            out.append(json);
            out.flush();
        }
        // 读取响应
        String res;
        try (InputStream inputStream = connection.getInputStream()) {
            res = IOUtils.toString(inputStream, "UTF-8");
        }
        connection.disconnect();
        return res;
    }

    public static String sendGet(String strURL) throws IOException {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.connect();
        connection.setConnectTimeout(DEFAULT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_TIMEOUT);
        // 读取响应
        String res;
        try (InputStream inputStream = connection.getInputStream()) {
            res = IOUtils.toString(inputStream, "UTF-8");
        }
        connection.disconnect();
        return res;
    }


    public static String sendPost(String urlStr, Map<String, Object> params) throws Exception {
        // post参数
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        //开始访问
        HttpURLConnection conn = (HttpURLConnection) (new URL(urlStr)).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(5000);
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0; ) {
            sb.append((char) c);
        }
        in.close();
        conn.disconnect();
        String responseStr = sb.toString();

        return responseStr;
    }

    public static String mapToUrl(String url, Map<String, String> map) {
        StringBuilder urlBuilder = new StringBuilder(url);
        for (Map.Entry<String, String> en : map.entrySet()) {
            if (urlBuilder.indexOf("?") == -1) {
                urlBuilder.append("?").append(en.getKey()).append("=").append(en.getValue());
            } else {
                urlBuilder.append("&").append(en.getKey()).append("=").append(en.getValue());
            }
        }
        return urlBuilder.toString();
    }

}
